import { createRouter, createWebHashHistory } from 'vue-router';
import { Toast } from 'vant';
import Store from '@/stores';
import { common } from '@/utils';
import Home from './modules/home';
import Login from './modules/login';

export const routes = [
  ...Home,
  ...Login,
  {
    path: '/:path(.*)*',
    name: '404',
    component: () => import('@/views/error/404'),
  },
];

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes,
});
const whiteList = ['/system', '/login', '/404'];

router.beforeEach((to, from, next) => {
  const token = Store.getters['common/getData']({ key: 'token', modules: 'common' });

  if (whiteList.includes(to.path)) {
    next();
  } else if (!token) {
    common.handleExit();
    next();
  } else {
    next();
  }
});

router.afterEach(() => {
  Toast.clear();
});

export const setupRouter = app => {
  app.use(router);
};

export default router;
